# 全局配置相关接口
from flask import Blueprint, request
import configparser
import os
from Logger import logger
from utils import get_global_config, MyResponse, handle_exception, handle_success

globalSetting = Blueprint('global', __name__)


@globalSetting.route('/file/getGlobalConfig', methods=['POST'])
def get_config():
    try:
        data = get_global_config()
    except Exception as err:  # 捕获异常
        return handle_exception(err, "程序异常")
    else:
        return handle_success(data, "文件获取成功")


@globalSetting.route('/file/saveGlobalConfig', methods=['POST'])
def save_config():
    try:
        params = request.json
        logger.info("params：%s", params)
        #path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static\global.ini')
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'global.ini')

        cf = configparser.ConfigParser()
        cf.read(path, "utf-8")
        cf.set("ProjectConfig", "root_path", params["rootPath"])  # 修改
        cf.set("ProjectConfig", "jmeter_path", params["jmeterPath"])  # 修改
        cf.set("ProjectConfig", "jm_version", params["jmVersion"])  # 修改
        cf.write(open(path, 'w', encoding='utf-8'))  # 写入

        global_config = get_global_config()
        root_path = global_config['rootPath']
        jmeter_path = global_config['jmeterPath']
        if not os.path.exists(root_path):
            return handle_exception("项目根路径错误", "项目根路径不存在")
        if not os.path.exists(jmeter_path):
            return handle_exception("Jmeter路径错误", "Jmeter路径不存在")
    except Exception as err:  # 捕获异常
        return handle_exception(err, "程序异常")
    else:
        return handle_success(request.json, "保存成功")
